<template>
    <div class="container">
        <div class="top_border">
            请选择你要上传到哪个期刊：
            <!-- 文件夹名称 -->
            <el-select v-model="folderName" class="m-2" placeholder="默认文件夹">
                <el-option v-for="item in folderList" :key="item.folderName" :label="item.folderName"
                    :value="item.folderName" />
            </el-select>
        </div>
        <div class="tuizhuai_box" :class="{ current_move_in: currentMove }" @dragenter="ondragenter"
            @dragleave="ondragleave" @dragover="ondragover" @drop="ondorp">
            <div class="havaIcoBox">
                <el-icon>
                    <UploadFilled />
                </el-icon><span>将目录文件或多个文件拖到此处进行扫描</span>
            </div>
            <div class="supportFileTypes">请上传您的pdf文件</div>
            <div>每个文件最大支持100M</div>
            <div class="inputUpload" @click="selectFile"></div>
        </div>
        <div class="upload_btn_box">
            <input type="file" ref="fileInputs" @change="SingleFileUpload" style="display: none;" multiple
                webkitdirectory mozdirectory odirectory>
            <input type="file" ref="fileInput" @change="ondorps" style="display: none;">
            <el-button @click="selectFile">选择单文件</el-button>
            <el-button @click="selectFiles">选择文件夹</el-button>
        </div>
        <!-- 文件上传列表 -->
        <div class="showUploadList" v-loading="loading">
            <el-table :data="upload_file" border height="100%">
                <el-table-column prop="name" label="文件名" />
                <!-- <el-table-column prop="type" label="类型" width="110" /> -->
                <el-table-column label="文件大小" width="110">
                    <template #default="scope">
                        <span>{{ formatFileSize(scope.row.size) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)" size="small">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="size" label="操作" width="110">
                    <template #default="scope">
                        <el-button :icon="Search" circle @click="viewPicture(scope.$index)" />
                        <el-button :icon="Delete" circle @click="removeFile(scope.$index)" />
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 上传按钮 -->
        <div class="uploadBtn_box">
            <el-button type="primary" @click="uploadImgs" :disabled="uploading">
                上传PDF({{ getUploadableCount() }})<el-icon>
                    <Upload />
                </el-icon>
            </el-button>
        </div>
        <!-- 大图弹窗 -->
        <div class="showLargeImage" v-show="WhetherToDisplay">
            <div class="closeButton" @click="WhetherToDisplay = false">×</div>
            <iframe v-if="showPdfUrl" :src="showPdfUrl" width="100%" height="100%"
                style="border: none; background-color: white;"></iframe>
        </div>
    </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Delete, Search } from '@element-plus/icons-vue'
import { getFolderList, uploadFile } from '@/api/upload'
const router = useRouter();

const folderName = ref('')
const folderList = ref('')

const loading = ref(false)
const uploading = ref(false) // 新增：整体上传状态

// 移除了 upperLimit 限制

/**
 * 点击上传按钮单图上传
 */
const fileInput = ref(null);
const fileInputs = ref(null);
const selectFile = () => {
    fileInput.value.click(); // 模拟点击单文件输入框
};
const selectFiles = () => {
    fileInputs.value.click(); // 模拟点击文件输入框
};
// 查看图片大图
const showPdfUrl = ref('') // 用于存储PDF预览的URL
const WhetherToDisplay = ref(false)
const viewPicture = (index) => {
    WhetherToDisplay.value = true
    // 使用URL.createObjectURL创建PDF文件的临时URL进行预览
    showPdfUrl.value = URL.createObjectURL(upload_file.value[index].file)
}
// 上传图片模拟
const uploadImgs = () => {
    // 如果没有选择文件夹,则提示用户选择文件夹
    if (!folderName.value) {
        ElMessage({
            message: "请选择你要上传到哪个期刊",
            type: 'warning',
        });
        return;
    }
    // 如果没有选择文件,则提示用户选择文件
    if (upload_file.value.length == 0) {
        ElMessage({
            message: "请选择你要上传的文件",
            type: 'warning',
        });
        return;
    }

    uploading.value = true;
    // 逐个上传文件
    uploadFilesSequentially(0);
}

// 逐个上传文件
const uploadFilesSequentially = async (index) => {
    if (index >= upload_file.value.length) {
        uploading.value = false;
        ElMessage({
            message: "所有文件操作完成！",
            type: 'success',
        });
        return;
    }

    const fileItem = upload_file.value[index];
    if (fileItem.status === 'completed' || fileItem.status === 'failed' || fileItem.status === 'duplicate') {
        // 如果文件已经处理过，跳过并处理下一个
        uploadFilesSequentially(index + 1);
        return;
    }

    try {
        const formData = new FormData();
        formData.append('files', fileItem.file);
        formData.append('folder', folderName.value);

        const res = await uploadFile(formData);

        if (res.code == 1) {
            // 上传成功
            upload_file.value[index].status = 'completed';
            // ElMessage.success(`文件 "${fileItem.name}" 上传成功`);
        } else {
            // 上传失败或重复
            if (res.code === 2) { // 假设后端返回 code=2 表示文件重复
                upload_file.value[index].status = 'duplicate';
                // ElMessage.info(`文件 "${fileItem.name}" 已存在，跳过上传`);
            } else {
                upload_file.value[index].status = 'failed';
                // ElMessage.error(`文件 "${fileItem.name}" 上传失败: ${res.msg || '未知错误'}`);
            }
        }
    } catch (error) {
        console.error('上传错误:', error);
        upload_file.value[index].status = 'failed';
        ElMessage.error(`文件 "${fileItem.name}" 上传异常: ${error.message}`);
    }

    // 延迟一秒后上传下一个文件，避免请求过于频繁
    setTimeout(() => {
        uploadFilesSequentially(index + 1);
    }, 100);
}

// 获取文件状态对应的标签类型
const getStatusType = (status) => {
    switch (status) {
        case 'completed':
            return 'success';
        case 'failed':
            return 'danger';
        case 'duplicate':
            return 'warning';
        default:
            return 'info';
    }
}

// 获取文件状态对应的文本
const getStatusText = (status) => {
    switch (status) {
        case 'completed':
            return '已完成';
        case 'failed':
            return '失败';
        case 'duplicate':
            return '重复';
        default:
            return '待上传';
    }
}

// 获取可上传的文件数量
const getUploadableCount = () => {
    return upload_file.value.filter(item => !['completed', 'failed', 'duplicate'].includes(item.status)).length;
}

// 选择文件夹
const ondorps = async (event) => {
    loading.value = true;
    const files = event.target.files;
    const uploadfile = upload_file.value;
    const maxSize = 100 * 1024 * 1024; // 100M转换为字节
    const allowedFormats = ['.pdf']; // 只允许PDF文件
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        // 判断文件大小是否超过上限
        if (file.size > maxSize) {
            ElMessage({
                message: "上传文件大小超过上限！每个文件大小不得超过100M.",
                type: 'warning',
            });
            continue; // 跳过当前文件，处理下一个文件
        }
        // 按文件类型和后缀名筛选，只添加PDF文件
        if (allowedFormats.some(format => file.name.toLowerCase().endsWith(format))) {
            // 初始化文件状态
            uploadfile.push({
                file: file,
                name: file.name,
                size: file.size,
                status: 'pending' // 新增：文件状态
            });
        }
        // 如果是文件夹，则读取文件夹内的内容
        if (file.isDirectory) {
            const fileEntries = await getFileEntries(file);
            for (let j = 0; j < fileEntries.length; j++) {
                const fileEntry = fileEntries[j];
                // 按文件类型和后缀名筛选，只添加PDF文件
                if (fileEntry.isFile && (fileEntry.file.type === 'application/pdf' || fileEntry.file.name.toLowerCase().endsWith('.pdf'))) {
                    uploadfile.push({
                        file: fileEntry.file,
                        name: fileEntry.file.name,
                        size: fileEntry.file.size,
                        status: 'pending' // 新增：文件状态
                    });
                }
            }
        }
    }
    upload_file.value = uploadfile
    fileInputs.value.value = ''
    loading.value = false;
};
// 选择文件夹（通过 webkitdirectory），并提取其中的所有 PDF 文件
const SingleFileUpload = (event) => {
    loading.value = true;
    const files = Array.from(event.target.files); // FileList 转为数组
    const uploadfile = []; // 最终上传的文件列表
    const maxSize = 100 * 1024 * 1024; // 单个文件最大 100MB

    for (const file of files) {
        if (file.name.toLowerCase().endsWith('.pdf')) {
            if (file.size > maxSize) {
                continue;
            }
            const pureFileName = file.name.split('/').pop() || file.name.split('\\').pop() || file.name;
            // 初始化文件状态
            uploadfile.push({
                file: file,
                name: pureFileName,
                size: file.size,
                status: 'pending' // 新增：文件状态
            });
        }
    }

    // 更新上传队列
    upload_file.value = uploadfile;

    // 清空 input，允许重新选择同一文件夹
    event.target.value = '';

    loading.value = false;

    // 成功提示
    ElMessage.success(`成功加载 ${uploadfile.length} 个 PDF 文件，准备上传。`);
};
// 移除文件
const removeFile = (index) => {
    upload_file.value.splice(index, 1);
}
const upload_file = ref([]);
// 是否有东西拖拽到上传框
const currentMove = ref(false)
// 拖拽上传拖拽API
// 移入时
const ondragenter = (e) => {
    currentMove.value = true
    e.preventDefault()
}
// 移动时
const ondragover = (e) => {
    e.preventDefault()
    currentMove.value = true
}
// 移出时
const ondragleave = (e) => {
    e.preventDefault()
    currentMove.value = false
}
let newUploadFile = 0;
// 拖拽上传处理
const ondorp = async (e) => {
    e.preventDefault();
    currentMove.value = false;
    loading.value = true;
    const files = upload_file.value;
    newUploadFile = upload_file.value.length;
    const validExtensions = new Set(['.pdf']); // 只允许PDF文件
    const traverseDirectory = async (entry) => {
        if (entry.isDirectory) {
            const reader = entry.createReader();
            const entries = await new Promise((resolve) => {
                reader.readEntries(resolve);
            });
            await Promise.all(entries.map((childEntry) => traverseDirectory(childEntry)));
        } else {
            const f = await new Promise((resolve) => {
                entry.file(resolve);
            });
            const fileSizeInBytes = f.size;
            const fileSizeInMB = fileSizeInBytes / (1024 * 1024); // 文件大小转换为MB
            const fileExtension = f.name.toLowerCase().slice(-4);
            if (fileExtension === '.pdf') { // 只允许PDF文件
                // ✅ 关键修改：确保文件名是纯净的
                const pureFileName = f.name.split('/').pop() || f.name.split('\\').pop() || f.name;
                
                files.push({
                    file: f,
                    name: pureFileName, // 使用纯净的文件名
                    size: f.size,
                    status: 'pending'
                });
            }
        }
    };
    console.log(e.dataTransfer.items);
    await Promise.all(
        Array.from(e.dataTransfer.items).map((item) => {
            const entry = item.webkitGetAsEntry();
            return traverseDirectory(entry);
        })
    );

    setTimeout(() => {
        upload_file.value = files;
        loading.value = false;
    }, 100);
};
// 计算文件大小
function formatFileSize(sizeInBytes) {
    if (sizeInBytes < 1024) {
        return sizeInBytes.toFixed(2) + " B";
    } else if (sizeInBytes < 1024 * 1024) {
        return (sizeInBytes / 1024).toFixed(2) + " KB";
    } else if (sizeInBytes < 1024 * 1024 * 1024) {
        return (sizeInBytes / (1024 * 1024)).toFixed(2) + " MB";
    } else {
        return (sizeInBytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
    }
}
const onKeyDown = () => {
    WhetherToDisplay.value = false
}
// 获取文件夹（期刊）列表
const initFolderList = async () => {
    const res = await getFolderList();
    if (res.code == 1) {
        folderList.value = res.data;
    } else {
        ElMessage({
            message: res.msg,
            type: 'error',
        })
    }
}
// 监听退出按钮
onMounted(() => {
    initFolderList();
    window.addEventListener('keydown', onKeyDown);
})
onUnmounted(() => {
    if (showPdfUrl.value) {
        URL.revokeObjectURL(showPdfUrl.value)
    }
    window.removeEventListener('keydown', onKeyDown)
})
</script>
<style scoped lang='scss'>
/* 样式保持不变 */
.top_border {
    border: 1px solid #fff0;
    width: 100%;
    margin: 0 auto;
    color: #999;
    font-size: 13px;
    display: flex;
    align-items: center;

    .el-select {
        flex: 1;
        max-width: 200px;
    }
}

.tuizhuai_box {
    position: relative;;
    color: #999;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin: 0 auto;
    margin-top: 10px;
    border-radius: 15px;
    height: 160px;
    line-height: 30px;
    border: 1px dashed #999;

    .havaIcoBox {
        display: flex;
        justify-content: center;
        align-items: center;

        .el-icon {
            font-size: 30px;
            margin-right: 5px;
        }
    }

    .supportFileTypes {
        text-align: center;
    }

    .inputUpload {
        cursor: pointer;
        position: absolute;
        width: 100%;
        height: 160px;
        line-height: 30px;
        opacity: 0;
    }
}

.current_move_in {
    border: 1px dashed rgb(128, 135, 241);
    background-color: #eee;
}

.upload_btn_box {
    margin: 10px 0;
}

.showUploadList {
    height: calc(100vh - 400px);
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #eee;
    overflow: auto;
    padding-bottom: 20px;
}

.uploadBtn_box {
    text-align: center;
    padding: 13px;
}

.showLargeImage {
    height: 100vh;
    width: 100vw;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    background-color: #0006;
    display: flex;
    justify-content: center;
    align-items: center;

    .closeButton {
        position: absolute;
        right: 20px;
        top: 20px;
        font-size: 30px;
        color: #fff;
        cursor: pointer
    }

    iframe {
        max-width: 80%;
        max-height: 90%;
        background-color: white;
    }
}
</style>